<?php
function fnmatch2($pattern, $string) {
	for ($op = 0, $npattern = '', $n = 0, $l = strlen($pattern); $n < $l; $n++) {
		switch ($c = $pattern[$n]) {
			case '\\':
				$npattern .= '\\' . @$pattern[++$n];
				break;
			case '.': case '+': case '^': case '$': case '(': case ')': case '{': case '}': case '=': case '!': case '<': case '>': case '|':
				$npattern .= '\\' . $c;
				break;
			case '?': case '*':
				$npattern .= '.' . $c;
				break;
			case '[': case ']': default:
				$npattern .= $c;
				if ($c == '[') {
					$op++;
				} else if ($c == ']') {
					if ($op == 0) return false;
					$op--;
				}
				break;
		}
	}

	if ($op != 0) return false;

	return preg_match('/' . $npattern . '/i', $string);
}

function crunch($list, $query) {
	$count09 = 0;
	$count10 = 0;
	
	foreach($list as $row) {
		if(fnmatch2("2009",$row['img_name'])){
			$list09[$count09] = $row;
			$count09++;
		}
		else {
			$list10[$count10] = $row;
			$count10++;
		}
	}
	$p09 = 0.0;
	$p10 = 0.0;
	$b09 = 0.0;
	$b10 = 0.0;
	$c09 = 0.0;
	$c10 = 0.0;
	
	foreach($list09 as $row) {
		$p09 += $row['people_num'];
		$b09 += $row['bikes_num'];
		$c09 += $row['cars_num'];
	}
	$p09 = $p09 / ($count09 - 1);
	$b09 = $b09 / ($count09 - 1);
	$c09 = $c09 / ($count09 - 1);
	foreach($list10 as $row) {
		$p10 += $row['people_num'];
		$b10 += $row['bikes_num'];
		$c10 += $row['cars_num'];
	}
	$p10 = $p10 / ($count10 - 1);
	$b10 = $b10 / ($count10 - 1);
	$c10 = $c10 / ($count10 - 1);
	
	echo "{$p09} {$p10} {$b09} {$b10} {$c09} {$c10}";

}

$query = $_GET['q'];
$sqlserver = mysql_connect('localhost','wustl_inst', 'wustl_pass');
if ($sqlserver != NULL) {
	$userdb = mysql_select_db('amos', $sqlserver);
	$d_query = urldecode($query);
	if (true) {
		$listquery = mysql_query("select * from HIT3", $sqlserver);
	}
	/*
	else {
		$d_query = urldecode($query);
		$listquery = mysql_query("select * from HIT2 where ".$d_query, $sqlserver);
	}
	*/
	$counter = 0;
	while($row = mysql_fetch_array($listquery, MYSQL_ASSOC)) {
		$list[$counter] = $row;
		$counter++;
	}
	
	crunch($list,$d_query);
}

?>